//
//  AssetCollectionViewCell.swift
//  YDPhotoPicker
//
//  Created by alyadan on 16/7/31.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import UIKit
import Photos
import MVVM_BaseViewController
import RxCocoa
import RxSwift
import YD_Util

class AssetCollectionViewCell: UICollectionViewCell {
    
    @IBOutlet weak var selectImage: UIImageView!
    @IBOutlet weak var photoImageView: UIImageView!
    @IBOutlet weak var videoImageView: UIImageView!
    
    @IBOutlet weak var selectBtn: UIButton!
    
    
    override var currentModel: AssetCollectionCellViewModel? {
        return viewModel.value as? AssetCollectionCellViewModel
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        photoImageView.contentMode = .scaleAspectFill
        // Initialization code
    }
    
    lazy  var option:PHImageRequestOptions = {
        let option = PHImageRequestOptions()
        //        option.deliveryMode = .FastFormat
//        option.resizeMode = .None
        //        option.synchronous = true
        return option
        
    }()
    
    
    @IBAction func selectImage(_ sender: Any) {
        currentModel?.tapSelect()
    }
    
     @objc override func bindModelData() {
        viewModel.asObservable()
            .flatMapLatest { (x :MVVM_BaseViewModel?) ->Observable<PHAsset?> in
                if let x = x as? AssetCollectionCellViewModel {
                    return x.photoAsset.asObservable()
                }
                return Observable<PHAsset?>.just(nil)
            }
            .subscribe(onNext: {[weak self] (x:PHAsset?) in
                if self == nil {
                   return
                }
                
                if let x = x {
                    
                    self?.selectBtn.isHidden = x.mediaType != .image
                    self?.selectImage.isHidden = self!.selectBtn.isHidden
                    
                    
                    self?.videoImageView.image = x.mediaType == .video ? self?.currentModel?.iconVideo : nil
                    self?.currentModel?.cacher?.requestImage(for: x, targetSize: CGSize.init(width: 100, height: 100), contentMode: .aspectFill, options: self!.option, resultHandler: { (img, y:[AnyHashable : Any]?) in
                        
                        if let degradedKey = y?[PHImageResultIsDegradedKey] as? NSNumber{
                            if  degradedKey.intValue  == 0{
                                self?.photoImageView.image = img
                            }
                        }
                    })
                }
                
            })
            .disposed(by: disposeBag)
        
        viewModel.asObservable()
            .flatMapLatest { (x :MVVM_BaseViewModel?) ->Observable<Bool> in
                if let x = x as? AssetCollectionCellViewModel {
                    return x.isSelected.asObservable()
                }
                return Observable<Bool>.just(false)
            }
            .subscribe(onNext: {[unowned self] (x:Bool) in
                self.selectImage.image =
                    x ? (self.currentModel?.imageSelected) : self.currentModel?.imageUnSelected
            })
            .addDisposableTo(disposeBag)
    }
    
}




class AssetCollectionCellViewModel: MVVM_BaseViewModel {
    
    var photoAsset = Variable<PHAsset?>(nil)
    var cacher:PHCachingImageManager?
    
    var isSelected = Variable<Bool>(false)
    
    let imageSelected = UIImage(named: "YD_Photo_Picker_bundle.bundle/hasSelected@3x.png")
    let iconVideo = UIImage(named: "YD_Photo_Picker_bundle.bundle/icon_video@3x.png")
    lazy var imageUnSelected:UIImage? = self.dataModel.maxSelectNum > 1 ? UIImage(named: "YD_Photo_Picker_bundle.bundle/select@3x.png") : nil
    
    init(photoAsset:PHAsset?, cacher:PHCachingImageManager? , parentViewModel:MVVM_BaseViewModel) {
        self.photoAsset.value = photoAsset
        self.cacher = cacher
        super.init(parentViewModel: parentViewModel)
        
    }
    
    var dataModel:YDPhotoShowAlbumVCModel {
        return parentViewModel as! YDPhotoShowAlbumVCModel
    }
    
    override func setupModel() {
        //a question
        Observable.combineLatest(dataModel.selectedAssets.asObservable(), photoAsset.asObservable(),
                                 resultSelector: { return ($0, $1) })
        .bindNext { [unowned self](x, y) in
            if let y = y {
               self.isSelected.value = x.contains(y)
            }
        }
        .addDisposableTo(disposeBag)
    }
    
    //MARK:-- interaction
    func tapSelect() {
        
        if let currentAsset = self.photoAsset.value{
            dataModel.modifySelectedAssets(with: currentAsset)
        }
    }
}
